package com.xjcs.saplingplan.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.blankj.utilcode.util.ActivityUtils
import com.xjcs.saplingplan.MainActivity
import com.xjcs.saplingplan.base.BaseVbActivity
import com.xjcs.saplingplan.databinding.ActivitySplashBinding
import com.xjcs.saplingplan.ui.activity.memo.MemoCreateActivity
import java.lang.ref.WeakReference

@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseVbActivity<ActivitySplashBinding>() {

    private val splashDelayMillis = 3000L

    private val mHandler = MyHandler(this)

    //使用WeakReference避免内存泄露
    private class MyHandler(activity: SplashActivity): Handler() {
        private val mActivity: WeakReference<SplashActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            mActivity.get()?.run {
                //跳转首页
//                ActivityUtils.startActivity(this, MainActivity::class.java)
                ActivityUtils.startActivity(this, MemoCreateActivity::class.java)
                finish()
            }
        }
    }

    override fun getViewBinding(): ActivitySplashBinding {
        return ActivitySplashBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.onCreate(savedInstanceState)
    }

    override fun initUi(savedInstanceState: Bundle?) {
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0){
            finish()
            return
        }
        //延迟跳转
        mHandler.sendEmptyMessageDelayed(0, splashDelayMillis)
    }

    override fun registerObserver() {
    }

    override fun initListener() {
    }

    override fun onDestroy() {
        super.onDestroy()
        //移除所有未处理的消息，避免内存泄露
        mHandler.removeCallbacksAndMessages(null)
    }

}